'use client';

import { useActions, useGlobalState } from '@/hooks';
import useMounted from '@/hooks/useMounted';
import Image from 'next/image';
import { LocalCache } from '@/utils/front/storage';
import { useEffect, useRef, useState } from 'react';
import { useSelector } from 'react-redux';
import { store } from '@/store';
import { showToast } from '@/components/Toast';
import ConfirmPopup from './ConfirmPopup';
import ComparePopup from '../ComparePopup';
import './CompareList.scss';
import Link from 'next/link';

const CompareList = () => {
  const [expand, setExpand] = useState(true);
  const toogleExpand = () => {
    setExpand(e => !e);
  };

  const {
    removeCompareList,
    restoreCompareList,
    setCompareList,
    setCompareOverMax,
  } = useActions();
  const { userInfo } = useGlobalState('user');
  const { compareList, compareMaxNum, compareOverMax } =
    useGlobalState('product');

  // console.log('🍄🍄🍄===Compare List Component run===');

  const handleRemoveCompare = (e: any) => {
    const dat = e?.currentTarget?.dataset;
    removeCompareList({ ...dat });
  };
  const [openConfirm, setOpenConfirm] = useState(false);
  const handleConfirmClear = () => {
    setCompareList([]);
  };
  const handleClearCompare = (e: any) => {
    setOpenConfirm(true);
  };

  const [openCompare, setOpenCompare] = useState(false);
  const handleToCompare = (e: any) => {
    setOpenCompare(true);
  };

  const handleCloseTips = (e: any) => {
    setCompareOverMax(false);
  };

  const initData = () => {
    // console.log('🍄🍄======COMPARE init====');
    const userKey = btoa(userInfo?.email || '');
    restoreCompareList(userKey);
  };
  const initDataRef = useRef(initData);
  initDataRef.current = initData;

  useEffect(() => {
    initDataRef.current();
  }, []);

  useEffect(() => {
    console.log('🍄🍄===Change compareList===', compareList);
  }, [compareList]);

  return (
    <div className="side-section compare-product">
      <div className="side-section-title" onClick={toogleExpand}>
        <span>Compare Products</span>
        {compareList?.length > 0 && (
          <button
            className="compare-product-button-clear"
            onClick={handleClearCompare}
          >
            Clear All
          </button>
        )}
      </div>
      <div
        className={`compare-product-content-wrapper ${expand ? 'content-expand' : 'content-collapse'}`}
      >
        <div
          className={`side-section-content compare-product-content thin-scroll-bar`}
        >
          {compareList?.length > 0 && (
            <div className="compare-product-list">
              {compareOverMax && (
                <div className="compare-product-list-limit-tips">
                  <div className="compare-product-list-limit-tips-info">
                    <span className="iconfont icon-warning-line"></span>Maximum
                    limit reached.
                  </div>
                  <span
                    className="compare-product-list-limit-tips-button"
                    onClick={handleCloseTips}
                  >
                    Ok
                  </span>
                </div>
              )}
              {Array.from(
                { length: compareMaxNum },
                (_, i) => compareList[i] || null
              )?.map((item: any, index: number) =>
                item ? (
                  <div key={index} className="compare-product-item">
                    <Link
                      className="compare-product-item-link"
                      href={`/product/${item.sku}`}
                    >
                      <div className="compare-product-image-wrapper">
                        <Image
                          fill={true}
                          sizes={'100%'}
                          priority={true}
                          src={item?.image}
                          alt={''}
                          className="compare-product-image"
                        />
                      </div>
                      <span
                        className="compare-product-title text-overflow-2"
                        title={item?.title}
                      >
                        {item?.title}
                      </span>
                    </Link>
                    <button
                      className="compare-product-button-remove"
                      data-sku={item?.sku}
                      onClick={handleRemoveCompare}
                    >
                      <span className="iconfont icon-close-line"></span>
                    </button>
                  </div>
                ) : (
                  <div key={index} className="compare-product-item-null"></div>
                )
              )}
            </div>
          )}
        </div>

        {compareList?.length > 1 && (
          <div className="compare-product-buttons">
            <button
              className="compare-product-button-compare"
              onClick={handleToCompare}
            >
              {' '}
              Compare
            </button>
          </div>
        )}
      </div>
      {compareList?.length == 0 && (
        <div className="compare-product-nulltips">
          You have no products to compare.
        </div>
      )}
      <ConfirmPopup
        open={openConfirm}
        onClose={() => setOpenConfirm(false)}
        onOk={handleConfirmClear}
        message="Are you sure to remove all products from the compare list?"
        title="Clear all Confirm"
      />
      <ComparePopup open={openCompare} onClose={() => setOpenCompare(false)} />
    </div>
  );
};

export default CompareList;
